package com.cy1640.damai;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private RadioGroup rgNavigations;
    private ViewPager vp_home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        vp_home= (ViewPager) findViewById(R.id.vp_home);
        rgNavigations= (RadioGroup) findViewById(R.id.rg_home);

        vp_home.setAdapter(new MyHomeAdapter(getSupportFragmentManager()));

        vp_home.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                ((RadioButton) rgNavigations.getChildAt(position)).setChecked(true);
            }
        });

        for (int i = 0; i <rgNavigations.getChildCount() ; i++) {
            rgNavigations.getChildAt(i).setTag(i);
            rgNavigations.getChildAt(i).setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View view) {
        vp_home.setCurrentItem((int) view.getTag());
    }

    class MyHomeAdapter extends FragmentPagerAdapter {

        public MyHomeAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return FragmentFactory.creatFragment(position);
        }

        @Override
        public int getCount() {
            return rgNavigations.getChildCount();
        }
    }

}